//
//  AppDelegate.m
//  MeiShiDa
//
//  Created by zby on 15/6/30.
//  Copyright (c) 2015年 zby. All rights reserved.
//

#import "AppDelegate.h"
#import "FirstViewController.h"
#import "MapViewController.h"
#import "HealthViewController.h"
#import "VideoViewController.h"
#import "MyViewController.h"
#import "DBmanager.h"
#import "FMDB.h"
@interface AppDelegate ()

@property (nonatomic,strong) FirstViewController* fvc;
@property (nonatomic,copy) NSString* xmlstr;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.

    [self createDB];
    [self launchTabBar];
    [self getXmlStrFromNet];
    return YES;
}

-(void)createDB{
    DBmanager* dbManager = [DBmanager shareDBmanager];
    FMDatabase* db = [dbManager openOrCreateDB];
    [db executeUpdate:@"create table if not exists ModelData1 (ModelID integer primary key,Title text,Picture text)"];
    [db executeUpdate:@"create table if not exists ModelData2 (ModelID integer primary key,Title text,Picture text,Descr text)"];
}

-(void)launchTabBar{
    self.fvc = [[FirstViewController alloc] init];
    UINavigationController* fnc = [[UINavigationController alloc] initWithRootViewController:self.fvc];
    fnc.tabBarItem.title = @"首页";
    fnc.tabBarItem.image = [UIImage imageNamed:@"shouye"];
    
    MapViewController* mvc = [[MapViewController alloc] init];
    UINavigationController* mnc = [[UINavigationController alloc] initWithRootViewController:mvc];
    mnc.tabBarItem.title = @"附近美食";
    mnc.tabBarItem.image = [UIImage imageNamed:@"ditu"];
    
    HealthViewController* hvc = [[HealthViewController alloc] init];
    UINavigationController* hnc = [[UINavigationController alloc] initWithRootViewController:hvc];
    hnc.tabBarItem.title = @"菜品";
    hnc.tabBarItem.image = [UIImage imageNamed:@"iconfont-meishi"];
    
    VideoViewController* vvc = [[VideoViewController alloc] init];
    UINavigationController* vnc = [[UINavigationController alloc] initWithRootViewController:vvc];
    vnc.tabBarItem.title = @"食频";
    vnc.tabBarItem.image = [UIImage imageNamed:@"shiping"];
    
    MyViewController* myvc = [[MyViewController alloc] init];
    UINavigationController* mync = [[UINavigationController alloc] initWithRootViewController:myvc];
    mync.tabBarItem.title = @"关于";
    mync.tabBarItem.image = [UIImage imageNamed:@"account"];
    
    UITabBarController* tabBarC = [[UITabBarController alloc] init];
    tabBarC.viewControllers = @[fnc,hnc,mnc,vnc,mync];
    self.window.rootViewController = tabBarC;
    
    // 首页动画

    UIImageView* showImage = [[UIImageView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    showImage.image = [UIImage imageNamed:@"1.png"];
    [self.window.rootViewController.view addSubview:showImage];
    [UIView animateWithDuration:3 delay:0 options:UIViewAnimationOptionCurveEaseInOut  animations:^{
        CGRect tempframe = [[UIScreen mainScreen] bounds];
        showImage.frame = CGRectMake(-tempframe.size.width/11, -tempframe.size.height/11, tempframe.size.width*13/11, tempframe.size.height*13/11);
    } completion:^(BOOL finished) {
        [showImage removeFromSuperview];
    }]; 
    
}


-(void)getXmlStrFromNet{
    NSURL* url = [NSURL URLWithString:[@"http://api.meishi.cc/v3/index.php" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest* request = [NSURLRequest requestWithURL:url];
    AFHTTPRequestOperation* operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        self.xmlstr = operation.responseString;
        [self jieXiXml];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    }];
    
    NSOperationQueue* queue = [[NSOperationQueue alloc] init];
    [queue addOperation:operation];
}
-(void)jieXiXml{
    int i = 0 ; int j = 0;
    DBmanager* dbManager = [DBmanager shareDBmanager];
    FMDatabase* db = [dbManager openOrCreateDB];
    self.arr1 = [NSMutableArray arrayWithCapacity:0];
    self.arr2 = [NSMutableArray arrayWithCapacity:0];
    GDataXMLDocument* document = [[GDataXMLDocument alloc] initWithXMLString:self.xmlstr options:001 error:nil];
    GDataXMLElement* root = [document rootElement];
    NSArray* arr1 = [root elementsForName:@"san_can"];
    NSArray* arr2 = [arr1[0] elementsForName:@"item"];
///////////////////////////////////////////////////////////////////
    for (id abc in arr2) {
        NSString* pic = [[abc elementsForName:@"titlepic"][0] stringValue];
        NSString* title = [[abc elementsForName:@"title"][0] stringValue];
        NSString* descr = [[abc elementsForName:@"descr"][0] stringValue];
        CellModel2* model = [[CellModel2 alloc] init];
        model.descr = descr;
        model.title = title;
        model.titlepic = pic;
        [self.arr2 addObject:model];
    }
    
///////////////////////////////////////////////////////////////////
        FMResultSet* resultSet2 = [db executeQuery:@"select * from ModelData2 where ModelID = ?",[NSNumber numberWithInt:1]];
        if ([resultSet2 next] == NO) {
            for (CellModel2* abc in self.arr2) {
                [db executeUpdate:@"insert into ModelData2 (ModelID,Title,Picture,Descr) values (?,?,?,?)",[NSNumber numberWithInt:i++],abc.title,abc.titlepic,abc.descr];
            }
        }
        else if ([resultSet2 next] == YES)
        {
            [db executeQuery:@"delete * from ModelData2"];
            for (CellModel2* abc in self.arr2) {
                [db executeUpdate:@"insert into ModelData2 (ModelID,Title,Picture,Descr) values (?,?,?,?)",[NSNumber numberWithInt:i++],abc.title,abc.titlepic,abc.descr];
            }
        }
    
///////////////////////////////////////////////////////////////////
    NSArray* arr3 = [root elementsForName:@"san_can_titles"];
    NSArray* arr4 = [arr3[0] elementsForName:@"item"];
    for (id abc in arr4) {
        NSString* pic = [[abc elementsForName:@"titlepic"][0] stringValue];
        NSString* title = [[abc elementsForName:@"title"][0] stringValue];
        CellModel1* model = [[CellModel1 alloc] init];
        model.title = title;
        model.titlepic = pic;
        [self.arr1 addObject:model];
    }
    
///////////////////////////////////////////////////////////////////
    FMResultSet* resultSet1 = [db executeQuery:@"select * from ModelData1 where ModelID = ?",[NSNumber numberWithInt:0]];
    if ([resultSet1 next] == NO) {
        for (CellModel1* abc in self.arr1) {
            [db executeUpdate:@"insert into ModelData1 (ModelID,Title,Picture) values (?,?,?)",[NSNumber numberWithInt:j++],abc.title,abc.titlepic];
        }
    }
    else if ([resultSet1 next] == YES)
    {
        [db executeQuery:@"delete * from ModelData1"];
        for (CellModel1* abc in self.arr1) {
            [db executeUpdate:@"insert into ModelData1 (ModelID,Title,Picture) values (?,?,?)",[NSNumber numberWithInt:j++],abc.title,abc.titlepic];
        }
    }
///////////////////////////////////////////////////////////////////
    self.fvc.arr1 = self.arr1;
    self.fvc.arr2 = self.arr2;
    [self.fvc.tableView reloadData];
    [db close];
 
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
